今天的題目在下面,要在不動下面的 code 的情況下,在上面加上自己的 code,就是用 destructure 的方式渲染成功。
今天在做的時候有打開昨日筆記 [Day 62] [React] ES6 Object & Array Destructuring 邊看邊寫。有更熟悉 Array 用 []
; object 用 {}
。
index.js:
ReactDOM.render(
<table>
<tr>
<th>Brand</th>
<th>Top Speed</th>
</tr>
<tr>
<td>{tesla.model}</td>
<td>{teslaTopSpeed}</td>
<td>{teslaTopColour}</td>
</tr>
<tr>
<td>{honda.model}</td>
<td>{hondaTopSpeed}</td>
<td>{hondaTopColour}</td>
</tr>
</table>,
document.getElementById("root")
);
practice data.js:
const cars = [
{
model: "Honda Civic",
//The top colour refers to the first item in the array below:
//i.e. hondaTopColour = "black"
coloursByPopularity: ["black", "silver"],
speedStats: {
topSpeed: 140,
zeroToSixty: 8.5
}
},
{
model: "Tesla Model 3",
coloursByPopularity: ["red", "white"],
speedStats: {
topSpeed: 150,
zeroToSixty: 3.2
}
}
];
先在 data.js 裡面加上 export default cars
,然後回到 index.js 看看 cars 裡面有什麼:
import React from "react";
import ReactDOM from "react-dom";
import cars from "./practice"
console.log(cars)
得到:
(2) [Object, Object]
0: Object
model: "Honda Civic"
coloursByPopularity: Array(2)
speedStats: Object
1: Object
model: "Tesla Model 3"
coloursByPopularity: Array(2)
speedStats: Object
const [honda, tesla] = cars;
/* 得到以下:
{model: "Honda Civic", coloursByPopularity: Array(2), speedStats: Object}
model: "Honda Civic"
coloursByPopularity: Array(2)
0: "black"
1: "silver"
speedStats: Object
topSpeed: 140
zeroToSixty: 8.5
data.js長這樣
//
{
model: "Tesla Model 3",
coloursByPopularity: ["red", "white"],
speedStats: {
topSpeed: 150,
zeroToSixty: 3.2
}
}................
//
/*第一個顏色
const {coloursByPopularity: [hondaTopColour] } = honda;
const {coloursByPopularity: [teslaTopColour] } = tesla;
/* 最高時速
const {speedStats: {topSpeed: teslaTopSpeed} } = tesla;
const {speedStats: {topSpeed: hondaTopSpeed} } = honda;
import React from "react";
import ReactDOM from "react-dom";
import cars from "./practice";
const [honda, tesla] = cars;
const {
speedStats: { topSpeed: hondaTopSpeed }
} = honda;
const {
speedStats: { topSpeed: teslaTopSpeed }
} = tesla;
const {
coloursByPopularity: [hondaTopColour]
} = honda;
const {
coloursByPopularity: [teslaTopColour]
} = tesla;
/* 以下是題目,不修改以下內容。
ReactDOM.render(
<table>
<tr>
<th>Brand</th>
<th>Top Speed</th>
<th>Top Colour</th>
</tr>
<tr>
<td>{tesla.model}</td>
<td>{teslaTopSpeed}</td>
<td>{teslaTopColour}</td>
</tr>
<tr>
<td>{honda.model}</td>
<td>{hondaTopSpeed}</td>
<td>{hondaTopColour}</td>
</tr>
</table>,
document.getElementById("root")
);